package com.epoint.juc.provider;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用JUC版的生产消费者模式  Lock + Condition
 */
public class JUCMsg {

    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2  = lock.newCondition();

    private int count = 0;

    public void send() throws InterruptedException {
        lock.lock();
        try{
            while (true){
                TimeUnit.MILLISECONDS.sleep(500);
                // 消费
                if(count > 0){
                    System.out.println("消费者当前数量：" + count--);
                    condition1.await();
                }

                condition2.signalAll();
            }
        }finally {
            lock.unlock();
        }
    }

    public void read() throws InterruptedException {
        lock.lock();
        try{
            while (true){
                TimeUnit.MILLISECONDS.sleep(500);
                // 生产
                if(count == 0){
                    System.out.println("生产者当前数量：" + count++);
                    condition2.await();
                }

                condition1.signalAll();
            }
        }finally {
            lock.unlock();
        }

    }
}
